<?php
class Controller_Pc_Api_Standard_Guide extends Controller_Pc_Api_Base
{
    public function before()
    {
        parent::before();
    }
    /**
     * @desc 获取轮播图
     */
    public function action_get_rolling_ad()
    {
        $result = DB::select()->from('xcx_ads')->where('prefix','=','s_guide_index')->order_by('displayorder','asc')->execute()->as_array();
        foreach($result as &$v){
            //判断产品类型
            if($v['typeid'] == 106){
                $v['url'] = '/stpage/guide/pages/guideServiceDetail/guideServiceDetail';
                $mod = DB::select('litpic')->from('guide_service');
            }
            if(!empty($mod)){
                $row = $mod ->where('id','=',$v['proid'])->execute()->current();
                //增加图片绝对访问地址
                $v['litpic'] = Model_Api_Standard_System::reorganized_resource_url($row['litpic']);
            }
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    //首页推荐
    public function action_index_recommend()
    {
        $result = Taglib_Guide::service(array('row' => 10));
        foreach ($result as &$item)
        {
            $item['litpic'] = Common::img($item['litpic']);
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }
    // 首页导游
    public function action_index_guide()
    {
        $result = Taglib_Guide::star_guide(array('row' => 10));
        foreach ($result as &$item)
        {
            $item['litpic'] = Common::img($item['litpic']);
            $item['age'] = Model_Guide::get_age($item['birth_date']);
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }
    // 获取导游详情
    public function action_get_guide_show()
    {
        $guideid = intval($this->request_body->content->guideid);
        $guide = Model_Api_Standard_Guide::info($guideid);
        $this->send_datagrams($this->client_info['id'], $guide, $this->client_info['secret_key']);
    }

    // 获取当前导游提供的服务
    public function action_get_user_service()
    {
        $guideid = intval($this->request_body->content->guideid);
        $result = Taglib_Guide::relation_service(array('guideid'=>$guideid));
        foreach ($result as &$item)
        {
            $item['litpic'] = Common::img($item['litpic']);
            $item['service_city'] = Model_Guide::get_service_city($guideid);
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    // 导游列表
    public  function action_guide_list()
    {
        $result = DB::select()->from('guide')->where('status','=',1)->order_by('displayorder','asc')->execute()->as_array();
        foreach ($result as &$guide)
        {
            $member = Model_Guide::get_info($guide['mid'], 'member');
            $guide['member'] = $member[0];
            $guide['member']['litpic'] = Common::img($guide['member']['litpic']);
            $guide['guide_card_pic'] = Common::img($guide['guide_card_pic']);
            $guide['age'] = Model_Guide::get_age($guide['member']['birth_date']);
            $guide['truename'] =   $guide['member']['truename'];
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }
    // 获取导游服务详情
    public  function action_get_service_show()
    {
        $id = intval($this->request_body->content->id);
        $productid = intval($this->request_body->content->productid);
        $id = empty($id) ? $productid : $id;
        $service = Model_Api_Standard_Guide::get_info($id);
        $service['enable_book'] = ($service['start_time'] > time() || $service['end_time'] < time()) ? 0 : 1;
        $this->send_datagrams($this->client_info['id'], $service, $this->client_info['secret_key']);
    }

    public function action_create_order()
    {
        $memberId = $this->request_body->content->memberid;//会员id
        Common::session('member', array('mid' => $memberId));
        $productId = $this->request_body->content->id;//导游id
        $linkMan = $this->request_body->content->linkman;//联系人姓名
        $linkTel = $this->request_body->content->linktel;//联系人电话
        $linkEmail = $this->request_body->content->linkemail;//联系人邮箱
        $remark = $this->request_body->content->remark;//订单备注
        $service_number = $this->request_body->content->dingnum;//服务人数
        $price = $this->request_body->content->price;//价格
        $curtime = time();//订单写入时间
        $totalPrice = 0 ;
        //整理订单
        $suit_arr = array();//子订单
        $startTime = strtotime($this->request_body->content->usedate);
        $endTime = strtotime($this->request_body->content->departdate);
        $info = DB::select()->from('guide_service')->where('id', '=', $productId)->execute()->current();
        $booking = true;//连续预订
        //判断接单日期是否符合选择日期
        if( $info['start_time'] > $startTime || ($info['end_time'] + 3600*24-1) < $endTime ){
            return $this->send_datagrams($this->client_info['id'], array('status' => false, 'msg' => '预定日期超过服务范围'), $this->client_info['secret_key']);
        }
        while (true)
        {
            $service = DB::select()
                ->from('guide_service_price')
                ->where('service_id', '=', $productId)
                ->and_where('day', '=', $startTime)
                ->and_where('number', '=', 1)
                ->execute()
                ->current();

            if ($service)
            {
                $service['price'] = Currency_Tool::price($service['price']);
                $service['dingnum'] = 1;
                $service['title'] = $info['title'];
                $service['peoplenum'] = $service_number;
                $service['usedate'] = $startTime;
                $suit_arr[] = $service;
                $totalPrice += $service['price'];
                $days[] = date('Y-m-d', $service['day']);
            }
            else
            {
                $booking = false;
                break;
            }
            $startTime += 86400;
            if ($endTime < $startTime)
            {
                break;
            }
        }
        if (!$booking) {
            $this->send_datagrams($this->client_info['id'], array('status' => false, 'msg' => '该产品当前日期已被预订'), $this->client_info['secret_key']);
        }
        //积分处理
        $needJifen = 0;
        $jifentprice = 0;
        $useJifen = 0;

        //支付方式
        $status = $info['paytype'] != 3 ? 1 : 0;
        $orderSn = Product::get_ordersn(106);
        $arr = array(
            'ordersn'       => $orderSn,
            'webid'         => 0,
            'typeid'        => 106,
            'litpic'        => $info['litpic'],
            'productautoid' => $info['id'],
            'productaid'    => $info['aid'],
            'productname'   => $info['title'],
            'price'         => $totalPrice,
            'childprice'    => 0,
            'oldprice'      => 0,
            'usedate'       => $days[0],
            'dingnum'       => 1,
            'childnum'      => 0,
            'oldnum'        => 0,
            'linkman'       => $linkMan,
            'linktel'       => $linkTel,
            'linkemail'     => $linkEmail,
            'jifentprice'   => $jifentprice,
            'jifenbook'     => $info['jifenbook_id'],
            'jifencomment'  => 0,
            'addtime'       => $curtime,
            'memberid'      => $memberId,
            'dingjin'       => $info['dingjin'],
            'paytype'       => $info['paytype'],
            'suitid'        => $info['id'],
            'usejifen'      => $useJifen,
            'needjifen'     => $needJifen,
            'departdate'    => $days[count($days) - 1],
            'status'        => $status,
            'remark'        => $remark,
            'isneedpiao'    => 0,
            'need_confirm'    => $info['paytype']==3?1:0,
        );
        /*--------------------------------------------------------------优惠券信息------------------------------------------------------------*/
        //优惠券判断
        $couponid = $this->request_body->content->couponid;
        if ($couponid)
        {
            $cid = DB::select('cid')->from('member_coupon')->where("id={$couponid}")->execute()->current();
            $totalprice = Model_Coupon::get_order_totalprice($arr);
            $ischeck = Model_Coupon::check_samount($couponid, $totalprice, $arr['typeid'], $arr['productautoid']);
            if ($ischeck['status'] == 1)
            {
                Model_Coupon::add_coupon_order($cid, $arr['ordersn'], $totalprice, $ischeck, $couponid);
            }
            else
            {
                $this->send_datagrams($this->client_info['id'], array('status' => false, 'msg' => 'coupon  verification failed!'), $this->client_info['secret_key']);
                exit;
            }
        }
        /*-----------------------------------------------------------------优惠券信息--------------------------------------*/
        //添加订单
        $out = St_Product::add_order($arr, 'Model_Guide', array_merge($arr, array('child_list' => $suit_arr)));

        if ($out)
        {
            //订单与导游关联
            $guideOrder = array('ordersn' => $arr['ordersn'], 'guide_id' => $info['guide_id']);
            DB::insert('guide_order', array_keys($guideOrder))->values(array_values($guideOrder))->execute();
            $orderInfo = Model_Member_Order::order_info($orderSn);
            foreach ($suit_arr as $row)
            {
                $child_model = ORM::factory('member_order_child');
                $child_model->pid = $orderInfo['id'];
                $child_model->suitid = $row['service_id'];
                $child_model->price = $row['price'];
                $child_model->title = $row['title'];
                $child_model->usedate = $row['usedate'];
                $child_model->departdate = $row['usedate'];
                $child_model->dingnum = $row['dingnum'];
                $child_model->peoplenum = $row['peoplenum'];
                $child_model->status = $status;
                $child_model->attachinfo = $row['attachinfo'];
                $child_model->addtime = $curtime;
                $child_model->ordersn = Product::get_sub_ordersn(106);
                $child_model->save();
            }
            $result = array(
                'status' => true,
                'orderinfo' => $orderInfo
            );

            St_Product::event($orderSn);

            $this->send_datagrams($this->client_info['id'],$result,$this->client_info['secret_key']);
        }
        else
        {
            $result = array(
                'status' => false,
                'msg' => $out['msg']
            );
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);

        }
    }

    //查询条件
    public function action_query_condition()
    {
        $result = array(
            'sort' => array(
                array('id' => 0, 'name' => '综合排序'),
                array('id' => 1, 'name' => '价格从低到高'),
                array('id' => 2, 'name' => '价格从高到低'),
                array('id' => 3, 'name' => '销量最高'),
                array('id' => 4, 'name' => '产品推荐')
            ),
            'attribute' => array(),
            'price' => array('name' => '价格', 'child' => array()),
        );

        //属性
        $result['attribute'] = DB::select('id', array('attrname', 'name'))->from('guide_attr')->where('pid', '=', 0)->and_where('isopen', '=', 1)->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')->execute()->as_array();
        foreach ($result['attribute'] as &$item)
        {
            $item['child'] = DB::select('id', array('attrname', 'name'))->from('guide_attr')->where('pid', '=', $item['id'])->and_where('isopen', '=', 1)->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')->execute()->as_array();

        }


        $result['price']['child'] = DB::select()->from('guide_pricelist')->where('lowerprice', '>=', 0)->order_by('lowerprice', 'asc')->execute()->as_array();

        //价格
        foreach ($result['price']['child'] as &$row)
        {
            if ($row['lowerprice'] == 0 && $row['highprice'] != 0)
            {
                $row['name'] = Currency_Tool::symbol() . $row['highprice'] . '以下';
            }
            else if ($row['highprice'] == '' || $row['highprice'] == 0)
            {
                $row['name'] = Currency_Tool::symbol() . $row['lowerprice'] . '以上';
            }
            else if ($row['lowerprice'] != '' && $row['highprice'] != '')
            {
                $row['name'] = Currency_Tool::symbol() . $row['lowerprice'] . '-' . Currency_Tool::symbol() . $row['highprice'];
            }
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    public function action_general_query()
    {
        $params = array(
            'pagesize' => $this->request_body->content->pagesize,
            'keyword' => $this->request_body->content->keyword,
        );
        $path = $this->request_body->content->path;
        list($params['destpy'],, $params['priceid'], $params['sorttype'], $params['attrid'], $params['page']) = explode('-', $path);
        $route_array = array(
            'destpy'   => is_null($params['destpy']) ? 'all' : $params['destpy'],
            'priceid'  => is_null($params['priceid']) ? 0 : intval($params['priceid']),
            'sex'      => 2,
            'sorttype' => is_null($params['sorttype']) ? 0 : intval($params['sorttype']),
            'attrid'   => is_null($params['attrid']) ? 0 : $params['attrid'],
            'p'        => $params['page'] > 0 ? $params['page'] : 1,
            'keyword'  => $params['keyword'],
        );
        $result = Model_Api_Standard_Guide::search_result($route_array, $params['pagesize'], 10);

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }
}